package com.meixiang.activity.homes.shopping;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.R;
import com.meixiang.activity.account.managers.myPurse.RechargeSucceedActivity;
import com.meixiang.activity.homes.service.OrderSubmissionSuccessfulActivity;
import com.meixiang.adapter.shopping.PayPlatformAdapter;
import com.meixiang.dialog.LoadingDialog;
import com.meixiang.dialog.TradersPasswordtKeyDialog;
import com.meixiang.entity.OrderResult;
import com.meixiang.entity.PaymentBean;
import com.meixiang.entity.services.PayResult;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.global.apiConfig;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.DesUtil;
import com.meixiang.util.TextViewUtil;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 美享收银台
 *
 * @author LZRUI
 */
public class CashierDeskActivity extends BaseActivity implements OnItemClick {

    private static final String TAG = "CashierDeskActivity";

    @Bind(R.id.tv_order_amount)
    TextView tvOrderAmount;
    @Bind(R.id.ry_pay_platform)
    RecyclerView ryPayPlatform;
    private LoadingDialog loadingDialog;
    private PayPlatformAdapter adapter;
    private IWXAPI api;

    private List<PaymentBean> mPayList;
    public static OrderResult mOrderResult;
    public static  String payType="";
    public static HashMap<String, Class> gotoActivityMap;

    public static final String ORDER_RESULT = "OrderResult";
    public static final String ORDER_TYPE = "orderType";//订单类型   SC：商城   FW：服务  PX:培训  用于再支付成功后页面做跳转的标识
    public static final String PAYMENT_TYPE = "paymentType"; // 1 订单支付 2 钱包充值 3 会员卡充值
    public static final String GOTO_ACTIVITY = "gotoActivity"; // 支付完成后跳转的activity
    public static final String MY_ORDER_SHOPPING_ORDER = "com.meixi.shopping.order"; //我的购物订单标识

    public static final String ORDER_PAY = "1"; // 订单支付
    public static final String PACKAGE_PAY = "2"; // 钱包充值
    public static final String CLUB_CARD_PAY = "3"; // 会员卡充值
    private int successType;

    public static final boolean isWX=false;
    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(activity, "支付成功", Toast.LENGTH_SHORT).show();
                        toSuccessActivity("ZFB");
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(activity, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_cashier_desk);
        ButterKnife.bind(this);
        api = WXAPIFactory.createWXAPI(this, apiConfig.WX_APP_ID);

        Intent intent = getIntent();
        if (intent != null) {
            mOrderResult = intent.getParcelableExtra(ORDER_RESULT);
            payType = intent.getStringExtra(PAYMENT_TYPE);
            gotoActivityMap = (HashMap<String, Class>) intent.getSerializableExtra(GOTO_ACTIVITY);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(CashierDeskActivity.this);
    }

    @Override
    protected void initTitle() {
        setTitle("美享生活收银台");
    }

    @Override
    protected void initView() {
        MXApplication.mApp.AddActivity(this);
        loadingDialog = new LoadingDialog(this);
        ryPayPlatform.setAdapter(adapter = new PayPlatformAdapter(this));
        ryPayPlatform.setLayoutManager(new LinearLayoutManager(this));
        adapter.setOnItemClick(this);
    }

    @Override
    protected void setData() {
        api = WXAPIFactory.createWXAPI(activity, apiConfig.WX_APP_ID);
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
//        Toast.makeText(CashierDeskActivity.this, String.valueOf(isPaySupported), Toast.LENGTH_SHORT).show();

        if (mOrderResult == null) return;
        String text = String.format(getString(R.string.order_amount), mOrderResult.getOrderAmount());
        TextViewUtil.setDiffColorText(tvOrderAmount, text, 4, text.length(), R.color.goods_price_red);
        getOrderData();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onItemClick(View view, final int position) {
        PaymentBean payment = mPayList.get(position);
        String payCode = payment.getPaymentCode().trim();
        if (payCode.equals("YE")) {
            new TradersPasswordtKeyDialog(this, "余额支付", mOrderResult.getOrderAmount(), new TradersPasswordtKeyDialog.OnCustomDialogListener() {
                @Override
                public void getPayPassWord(TradersPasswordtKeyDialog paymentKeyDialog, String password) {
                    pay("YE", password);
                }
            });
        } else if (payCode.equals("HYC")) {

            new TradersPasswordtKeyDialog(this, "会员卡支付", mOrderResult.getOrderAmount(), new TradersPasswordtKeyDialog.OnCustomDialogListener() {
                @Override
                public void getPayPassWord(TradersPasswordtKeyDialog paymentKeyDialog, String password) {
                    pay("HYC", password);
                }
            });

        } else {
            pay(payCode, null);
        }



    }

    /**
     * 获取支付方式列表
     */
    private void getOrderData() {

        HttpParams params = new HttpParams();
        params.put("paymentType", payType); // 1 订单支付 2 钱包充值 3 会员卡充值
        params.put("orderId", mOrderResult.getOrderId());
        HttpUtils.post(Config.PAY_STY_LIST, TAG, params, new HttpCallBack(CashierDeskActivity.this) {

            @Override
            public void onBefore(BaseRequest request) {
                if (loadingDialog != null && !loadingDialog.isShowing())
                    loadingDialog.show();
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                if (loadingDialog != null && loadingDialog.isShowing())
                    loadingDialog.dismiss();
            }

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                mPayList = AbJsonUtil.fromJson(result.optString("paymentList"), new TypeToken<List<PaymentBean>>() {
                });
                adapter.refreshData(mPayList);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(activity, message);
            }
        });
    }

    /**
     * 支付
     *
     * @param payCode 支付平台
     * @param payPwd  支付密码（余额支付需要传）
     */
    private void pay(final String payCode, String payPwd) {

        HttpParams params = new HttpParams();
        params.put("orderId", mOrderResult.getOrderId());
        params.put("paymentCode", payCode);
        params.put("paymentType", payType);

        if (!TextUtils.isEmpty(payPwd)) {
            params.put("tradePasswd", DesUtil.md5(payPwd));
        }

        Log.i("lzrtest", "支付： " + params.toString());

        HttpUtils.post(Config.PAYSTYLE_WX_PAY, TAG, params, new HttpCallBack(CashierDeskActivity.this) {

            @Override
            public void onBefore(BaseRequest request) {
                if (loadingDialog != null && !loadingDialog.isShowing())
                    loadingDialog.show();
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                if (loadingDialog != null && loadingDialog.isShowing())
                    loadingDialog.dismiss();
            }

            @Override
            public void onSucceed(final JSONObject result, String code, String message) {

                if (payCode.equals("WX")) {

                    // 微信
                    PayReq req = new PayReq();
                    req.appId = result.optString("appid");
                    req.partnerId = result.optString("partnerid");
                    req.prepayId = result.optString("prepayid");
                    req.nonceStr = result.optString("noncestr");
                    req.timeStamp = result.optString("timestamp");
                    req.packageValue = result.optString("package");
                    req.sign = result.optString("sign");
                    Log.e("TAG","微信支付="+req.sign.toString());
                    api.sendReq(req);
//
//
                } else if (payCode.equals("ZFB")) {
                    Tool.showTextToast(activity, message);
                    Runnable payRunnable = new Runnable() {
                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(activity);
                            String pay = alipay.pay(result.optString("payInfo"), true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = pay;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();

                }else{
                    Tool.showTextToast(activity, message);
                    toSuccessActivity(payCode);
                }

            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(activity, message);
            }
        });
    }


    /**
     * 跳转到对应的支付成功Activity
     * @param payCode
     */
    private void toSuccessActivity(String payCode) {
        Intent intent=new Intent();
        if (payType.equals(ORDER_PAY)) {
            // 订单支付，跳转到订单支付成功页面
            intent .setClass(CashierDeskActivity.this, OrderSubmissionSuccessfulActivity.class);
            if(!AbStrUtil.isEmpty(getIntent().getStringExtra(GlobalType.ORDER_PAYMENT_TYPE))
                &&MY_ORDER_SHOPPING_ORDER.equals(getIntent().getStringExtra(GlobalType.ORDER_PAYMENT_TYPE))){
                notifyOrderList();
            }
            intent.putExtra("payCode",payCode);
            intent.putExtra(ORDER_TYPE,getIntent().getStringExtra(ORDER_TYPE));
        } else {
            // 钱包充值、会员卡充值，跳转到充值成功页面
            intent .setClass(CashierDeskActivity.this, RechargeSucceedActivity.class);
        }
        intent.putExtra(ORDER_RESULT, mOrderResult);
        intent.putExtra(GOTO_ACTIVITY, gotoActivityMap);
        startActivity(intent);

    }

    private void notifyOrderList(){
        Intent intent=new Intent(GlobalType.ORDER_DETAIL_OPERATION);
//        intent.putExtra("orderId",orderId);
        sendBroadcast(intent);
        this.finish();
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        if(WXPayEntryActivity.msg.equals("支付成功")){
//            toSuccessActivity(payCode);
//        }
//    }
}
